/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAL;

import DTO.DTOUser;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author Pham
 */
public class DALUser {
    ConnectionDB conn;
    public DALUser(){
        conn = new ConnectionDB();
    }
    
    //method check login
    public DTOUser checkLogin(String username, String password)
    {
        try{
            DTOUser dtoUser = null;
            String querySelect = "SELECT * FROM `user` WHERE username = ? AND password = ?";
            PreparedStatement stmt = conn.getConnectionDB().prepareStatement(querySelect);
            stmt.setString(1, username);
            stmt.setString(2, conn.getMD5(password));
            ResultSet rs = stmt.executeQuery();
            while(rs.next())
            {
                dtoUser = new DTOUser(rs);
            }
            return dtoUser;
        }
        catch(Exception ex){
            System.err.printf(ex.getMessage());
            return null;
        }
    }

    public boolean changePassword(String username, String oldPass, String newPass) {
        try{
            DTOUser dtoUser = checkLogin(username, oldPass);
            if(dtoUser == null){
                return false;
            }
            else
            {
                String queryUpdate = "update `user` set password = ? where username = ?";
                PreparedStatement pstmt = conn.getConnectionDB().prepareStatement(queryUpdate);
                pstmt.setString(1, conn.getMD5(newPass));
                pstmt.setString(2, username);
                return pstmt.executeUpdate() == 1;
            }
        }
        catch(Exception ex){
            System.err.printf(ex.getMessage());
            return false;
        }
        
    }
}
